<?php

namespace Admin\Controller;

use Common\Common\AdminController;
use Common\Utils;
use Common\Top;

class ProviderFinanceController extends AdminController
{


    public function index()
    {
        $info = M('provider')->where('id=' . session('entity_id'))->find();

        $entityType = Top::EntityTypeProvider;
        $entityId = $info['id'];
        $amount = Utils::getFrozenFen($entityType, $entityId);
        $availableBalance = Utils::getProviderAvailableFen($entityId);

        $this->assign('amount', $amount);
        $this->assign('availableBalance', $availableBalance);
        $this->assign('info', $info);
        $this->display();
    }

    //供应商提现申请页
    public function withdraw()
    {
        $provider = M('provider');
        $info = $provider->where('id=' . session('entity_id'))->find();
        $entityType = Top::EntityTypeProvider;
        $entityId = $info['id'];
        $amount = intval(I('amount'));

        if (IS_POST && IS_AJAX) {
            $operatorId = I('operator_id');

            $operatorInfo = M('operator')->where("id = '{$operatorId}'")->field('id,display_name')->find();

            $where['entity_type'] = $entityType;
            $where['entity_id'] = $entityId;
            $where['operator_id'] = $operatorId;

            $applyStateWait = Top::ApplyStateWait;
            $applyStatePass = Top::ApplyStatePass;

            $withdrawList = M('account_withdraw')->where($where)->where("state = '{$applyStateWait}' or state = '{$applyStatePass}'")->field('id,amount,state')->select();
            $sum = 0;
            foreach ($withdrawList as $key => $vo) {
                $sum += $vo['amount'];
            }

            $tourOrderList = M('order_tour')->where("provider_id = '{$entityId}' && provider_operator_id = '{$operatorId}' && (state = 9 || state = 10 || state = 12)")->select();

            foreach ($tourOrderList as $k => $v) {
                if ($v['fullpay_time'] != '') {
                    $sum += $v['price_total'] + $v['price_adjust'] - Utils::CalcCommission($v['commission_rate'], $v['price_total'] + $v['price_adjust']);
                } else {
                    $sum += $v['prepay_amount'] - Utils::CalcCommission($v['commission_rate'], $v['prepay_amount']);
                }
            }

            $accountBalanceInfo = M('provider_account')->where("provider_id = '{$entityId}' && operator_id = '{$operatorId}'")->find();
            $accountBalance = $accountBalanceInfo['account_balance'];
            //可用余额
            $availableBalance = $accountBalance - $sum;

            if ($info['account_state'] == Top::StateEnabled && $info['state'] == Top::StateEnabled) {
                if ($amount <= $availableBalance && $amount > 0) {
                    //插入account_withdraw表
                    $data = array(
                        'operator_id' => I('operator_id'),
                        'account' => $accountBalanceInfo['account'],
                        'entity_type' => session('entity_type'),
                        'entity_name' => $info['name'],
                        'full_name' => $info['full_name'],
                        'entity_id' => session('entity_id'),
                        'bank_name' => $info['bank_name'],
                        'bank_account' => $info['bank_account'],
                        'amount' => I('amount'),
                        'create_time' => date('Y-m-d H:i:s', time()),
                        'state' => Top::ApplyStateWait,
                        'settlement_interval' => $info['settlement_interval'],
                    );

                    $withdraw = M('account_withdraw');

                    $postCode = I('code');
                    $code = session('applyWithDrawCode');

                    if ($postCode == $code) {
                        session('applyWithDrawCode', null);
                        $withdrawInfo = $withdraw->add($data);
                    }

                    if ($withdrawInfo) {
                        $data['status'] = 1;
                        $data['msg'] = "提现申请成功！为不影响提现进程，请尽快向 " .$operatorInfo['display_name']. " 提交发票";
                        $this->ajaxReturn($data);
                    } else {
                        $data['status'] = 0;
                        $data['msg'] = '系统出错了';
                        $this->ajaxReturn($data);
                    }
                } else {
                    $data['status'] = 2;
                    $data['msg'] = '对不起提现失败，提现金额大于可用余额';
                    $this->ajaxReturn($data);
                }
            } else {
                $data['status'] = 3;
                $data['msg'] = '对不起提现失败，请检查当前账户状态或者联系运营商 010-12345678';
                $this->ajaxReturn($data);
            }
        } else {
            $_SESSION['applyWithDrawCode'] = 400;
            $withDrawList = M('provider_account')->where("provider_id = '{$entityId}'")->field('id,provider_id,account_balance,operator_id')->order('operator_id')->select();

            $operatorList = M('operator')->field('id,invoice_title')->select();

            $where['entity_type'] = $entityType;
            $where['entity_id'] = $entityId;
            $applyStateWait = Top::ApplyStateWait;
            $applyStatePass = Top::ApplyStatePass;
            $frozenWithdrawList = M('account_withdraw')->where($where)->where("state = '{$applyStateWait}' or state = '{$applyStatePass}'")->field('id,operator_id,sum(amount) frozen_amount,state')->order('operator_id')->group('operator_id')->select();
            

            foreach ($withDrawList as $key => $vo) {
                foreach ($operatorList as $k => $v) {
                    if ($vo['operator_id'] == $v['id']) {
                        $where['operator_id'] = $vo['operator_id'];
                        $withdrawNewList[$key] = M('account_withdraw')->where($where)->where("state = '{$applyStateWait}' or state = '{$applyStatePass}'")->field('id,entity_id,operator_id,amount,state')->order('operator_id')->sum('amount');
                        $list[$key]['id'] = $vo['id'];
                        $list[$key]['operator_id'] = $vo['operator_id'];
                        $list[$key]['account_balance'] = $vo['account_balance'];
                        $list[$key]['invoice_title'] = $v['invoice_title'];
                    }
                }
            }

            $tourOrderList = M('order_tour')->where("provider_id = '{$entityId}' && (state = 9 || state = 10 || state = 12)")->select();
            foreach ($withDrawList as $ki => $vi) {
                foreach ($frozenWithdrawList as $kt => $vt) {
                    if ($vi['operator_id'] == $vt['operator_id']) {
                        $list[$ki]['frozen_amount'] = $vt['frozen_amount'];
                    }
                }
            }

            foreach ($tourOrderList as $kk => $vv) {
                foreach ($withDrawList as $kf => $vf) {
                    if ($vv['provider_operator_id'] == $vf['operator_id']) {
                        if ($vv['fullpay_time'] != '') {
                            $list[$kf]['order_tour_frozen_amount'] += $vv['price_total'] + $vv['price_adjust'] - Utils::CalcCommission($vv['commission_rate'], $vv['price_total'] + $vv['price_adjust']);
                        } else {
                            $list[$kf]['order_tour_frozen_amount'] += $vv['prepay_amount'] - Utils::CalcCommission($vv['commission_rate'], $vv['prepay_amount']);
                        }
                    }
                }
            }

            $amount = Utils::getProviderAllFrozenFen($entityType, $entityId);

            $this->assign('amount', $amount);
            $this->assign('list', $list);
            $this->assign('info', $info);
            $this->display();
        }
    }


    public function withdrawInfo()
    {
        $entityId = session('entity_id');
        $entityType = session('entity_type');
        $startTime = !empty(I('start_time')) ? I('start_time') : date("2015-05-01", time());
        $endTime = !empty(I('end_time')) ? I('end_time') : date('Y-m-d', time());

        $where = "entity_id = '{$entityId}' && entity_type = '{$entityType}' && (create_time >= '{$startTime} {$this->dateStart}' && create_time <= '{$endTime} {$this->dateEnd}')";
        $pageInfo = Utils::pages('account_withdraw', $where, C('PAGE_SET'), $order = " id desc ");

        if ($pageInfo['info']) {
            $this->info = $pageInfo['info'];
            $this->page = $pageInfo['page'];
        } else {
            $this->msg = '当前没有记录';
        }

        $this->assign('startTime', $startTime);
        $this->assign('endTime', $endTime);
        $this->display();
    }


    public function transaction()
    {
        $entityId = session('entity_id');
        $entityType = session('entity_type');
        $where = "entity_id = '{$entityId}' and entity_type = '{$entityType}'";

        $list = M('account_transaction')->where($where)->group('operator_id')->select();

        foreach ($list as $k => $v) {
            $operatorInfo[$k] = M('operator')->where("id = " . $v['operator_id'])->find();
        }

        $this->assign('info', $operatorInfo);
        $this->display();
    }



    public function details()
    {
        $entityId = session('entity_id');
        $entityType = session('entity_type');
        $operatorId = I('get.oid');
        $name = trim(I('names'));
        $startTime = !empty(I('start_time')) ? I('start_time') : date("2015-05-01", time());
        $endTime = !empty(I('end_time')) ? I('end_time') : date('Y-m-d', time());
        $operatorInfo = M('operator')->where("id = '{$operatorId}'")->find();

        if ($name) {
            $where = "entity_id = '{$entityId}' and entity_type = '{$entityType}' && operator_id = '{$operatorId}' && action like '%%$name%%' && (create_time >= '{$startTime} {$this->dateStart}' && create_time <= '{$endTime} {$this->dateEnd}')";
        } else {
            $where = "entity_id = '{$entityId}' and entity_type = '{$entityType}' && operator_id = '{$operatorId}' && (create_time >= '{$startTime} {$this->dateStart}' && create_time <= '{$endTime} {$this->dateEnd}')";
        }

        $pageInfo = Utils::pages('account_transaction', $where, C('PAGE_SET'), $order = " id desc ");

        if ($pageInfo['info']) {
            $this->info = $pageInfo['info'];
            $this->page = $pageInfo['page'];
        } else {
            $this->msg = '当前没有记录';
        }

        $this->assign('startTime', $startTime);
        $this->assign('endTime', $endTime);
        $this->assign('name', $name);
        $this->assign('operatorInfo', $operatorInfo);
        $this->display();
    }

}
